package info

import (
	"encoding/json"
	"fmt"
	"reflect"
	"strconv"
	"time"

	//"github.com/StackExchange/wmi"
	"github.com/yusufpapurcu/wmi"
	"gopkg.in/ini.v1"
)

type ProcesserInfo struct {
	AddressWidth                            int16     `json:"操作系统位数" `
	Architecture                            int16     `json:"体系结构"`
	AssetTag                                string    `json:"资产标记"`
	Availability                            int16     `json:"可用性"`
	Caption                                 string    `json:"说明"`
	Characteristics                         uint32    `json:"特征"`
	ConfigManagerErrorCode                  uint32    `json:"Manager错误代码"`
	ConfigManagerUserConfig                 bool      `json:"是否是用户配置"`
	CpuStatus                               uint16    `json:"使用情况"`
	CreationClassName                       string    `json:"范围计算机属性值"`
	CurrentClockSpeed                       uint32    `json:"当前速度(MHz)"`
	CurrentVoltage                          uint16    `json:"电压(十伏)"`
	DataWidth                               uint16    `json:"处理器位数"`
	Description                             string    `json:"描述"`
	DeviceID                                string    `json:"标识"`
	ErrorCleared                            bool      `json:"报告错误是否明确"`
	ErrorDescription                        string    `json:"错误详细信息"`
	ExtClock                                uint32    `json:"外部时钟频率(MHz)"`
	Family                                  uint16    `json:"系列"`
	InstallDate                             time.Time `json:"安装日期"`
	L2CacheSize                             uint32    `json:"L2缓存大小(KB)"`
	L2CacheSpeed                            uint32    `json:"L2缓存时钟速度"`
	L3CacheSize                             uint32    `json:"L3缓存大小(KB)"`
	L3CacheSpeed                            uint32    `json:"L3缓存时钟速度"`
	LastErrorCode                           uint32    `json:"逻辑设备报告最后一个错误代码"`
	Level                                   uint16    `json:"级别"`
	LoadPercentage                          uint16    `json:"负载容量"`
	Manufacturer                            string    `json:"造商名称"`
	MaxClockSpeed                           uint32    `json:"最大速度(MHz)"`
	Name                                    string    `json:"名称"`
	NumberOfCores                           uint32    `json:"核心数"`
	NumberOfEnabledCore                     uint32    `json:"已启用核心数"`
	NumberOfLogicalProcessors               uint32    `json:"逻辑处理器数"`
	OtherFamilyDescription                  string    `json:"处理器系列类型"`
	PartNumber                              string    `json:"部件号"`
	PNPDeviceID                             string    `json:"即插即用逻辑设备设备标识符"`
	PowerManagementCapabilities             []uint16  `json:"电源相关"`
	PowerManagementSupported                bool      `json:"是否启用电源管理功能"`
	ProcessorId                             string    `json:"处理器信息"`
	ProcessorType                           uint16    `json:"主要功能"`
	Revision                                uint16    `json:"修订"`
	Role                                    string    `json:"角色"`
	SecondLevelAddressTranslationExtensions bool      `json:"是否支持于虚拟化地址转换扩展"`
	SerialNumber                            string    `json:"序列号"`
	SocketDesignation                       string    `json:"芯片插槽类型"`
	Status                                  string    `json:"状态"`
	StatusInfo                              uint16    `json:"逻辑设备状态"`
	Stepping                                string    `json:"修订级别"`
	SystemCreationClassName                 string    `json:"计算机属性值"`
	SystemName                              string    `json:"系统名称"`
	ThreadCount                             uint32    `json:"套接字线程数"`
	UniqueId                                string    `json:"全局唯一标识符"`
	UpgradeMethod                           uint16    `json:"CPU套接字信息"`
	Version                                 string    `json:"修订号"`
	VirtualizationFirmwareEnabled           bool      `json:"是否开启虚拟化扩展"`
	VMMonitorModeExtensions                 bool      `json:"虚拟机监视器扩展"`
	VoltageCaps                             uint32    `json:"电压功能"`
}

func CPUInfo() (process []ProcesserInfo, err error) {
	err = wmi.Query("Select * from Win32_Processor", &process)
	if err != nil {
		return nil, err
	}
	return process, nil
}
func JsonCPUInfo() (f []byte, err error) {
	cpu, err := CPUInfo()
	if err != nil {
		return f, err
	}
	t, jsonerr := json.Marshal(cpu)
	if jsonerr != nil {
		return f, jsonerr
	}
	return t, nil

}
func MapCPUInfo() (data []map[string]interface{}, err error) {
	//data := make([]map[string]interface{}, 0)
	t, err1 := JsonCPUInfo()
	if err1 != nil {
		return data, err1
	}
	json.Unmarshal(t, &data)
	cfg, err1 := ini.Load("./info/processorconfig.ini")
	if err1 != nil {
		return data, err
	}
	list := []string{"体系结构", "系列", "主要功能", "CPU套接字信息", "可用性", "特征", "使用情况"}
	for _, v := range data {
		for _, vl := range list {
			if a, ok := v[vl].(float64); ok {
				v[vl] = cfg.Section(cfg.Section("").Key(vl).String()).Key(strconv.Itoa(int(a))).String()
			} else {
				continue
			}

		}
		//fmt.Println(cfg.Section(d.String()).Key(fmt.Sprintf("%v", v1)))
	}
	return data, nil

}

// 英文字段
func JsonCPUInfoEn() (s string, err error) {
	cpu, err := CPUInfo()
	if err != nil {
		return "", err
	}

	jsonData := make(map[string]interface{})
	jsonDataList := make([]map[string]interface{}, 0)
	//cpu1 := cpu[0]
	for _, cpu1 := range cpu {
		cpuType := reflect.TypeOf(cpu1)
		cpuValue := reflect.ValueOf(&cpu1)
		for i := 0; i < cpuType.NumField(); i++ {
			field := cpuType.Field(i)                                   // 获取字段信息
			jsonData[field.Name] = cpuValue.Elem().Field(i).Interface() // 将字段值添加到 JSON 数据中
			fieldValue := cpuType.Field(i).Tag                          // 获取字段的值
			println(field.Name)
			println("================")
			println(fieldValue)
			//println(field.Name, fieldValue.Get("json"))
			// 将字段值添加到 JSON 数据中，不使用 tag 标签指定 JSON 键的名称
		}
		jsonDataList = append(jsonDataList, jsonData)
	}

	t, jsonErro := json.Marshal(jsonDataList)
	if jsonErro != nil {
		return "", jsonErro
	}
	return string(t), nil

}

type CIM_LogicalDevice struct {
	Caption                     string
	Description                 string
	InstallDate                 time.Time
	Name                        string
	Status                      string
	Availability                uint16
	ConfigManagerErrorCode      uint32
	ConfigManagerUserConfig     bool
	CreationClassName           string
	DeviceID                    string
	PowerManagementCapabilities []int32
	ErrorCleared                bool
	ErrorDescription            string
	LastErrorCode               uint32
	PNPDeviceID                 string
	PowerManagementSupported    bool
	StatusInfo                  uint16
	SystemCreationClassName     string
	SystemName                  string
}

func LogicalDeviceInfo() {
	var info []CIM_LogicalDevice
	err1 := wmi.Query("Select * from CIM_LogicalDevice", &info)
	if err1 != nil {

		fmt.Printf("错误:%s\n", err1)
		return
	}
	fmt.Printf("%#v", info)
}
